package cn.edu.hhu.servlet.admin;

import cn.edu.hhu.service.AdminService;
import cn.edu.hhu.service.Impl.AdminServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @anthor: lddd
 * @date: 2020/5/17 - 13:54
 * @description:
 **/
@WebServlet("/admin/addStudentsServlet")
public class AddStudentsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getParameter("type") == null) {
            doGet(request, response);
            return;
        }
        if (request.getParameter("type").equals("single")) {
            //1获取参数
            String sid = request.getParameter("sid");
            String sname = request.getParameter("sname");
            //2调用service插入
            AdminService adminService = new AdminServiceImpl();
            System.out.println(sid + "   " + sname);
            if (!adminService.addSingleStudent(sid, sname)) {
                request.setAttribute("msg", "添加失败！");
            }
        } else if (request.getParameter("type").equals("multi")) {
            String input = request.getParameter("sid_and_names");
            if (input == null || input.equals("")) {
                doGet(request, response);
                return;
            }
            String[] students = input.split("\n");
            StringBuffer msg = new StringBuffer();
            AdminService adminService = new AdminServiceImpl();
            for (String student : students) {
                student = student.strip();
                int split = student.indexOf("\t");
                if (split == -1) {
                    split = student.indexOf(' ');
                }
                if (split == -1) {
                    msg.append(student).append("添加失败！<br>");
                } else {
                    String sid = student.substring(0, split).strip();
                    String sname = student.substring(split + 1).strip();
                    if (!adminService.addSingleStudent(sid, sname)) {
                        msg.append(student).append("添加失败！<br>");
                    }
                }
                request.setAttribute("msg", msg);
            }
        }
        //3跳转到查询所有的servlet
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/admin/addStudent.jsp").forward(request, response);
    }
}
